//
//  AppController.m
//  SpeakLine
//
//  Created by Beomjun Kim on 09. 08. 01.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"


@implementation AppController

- (id)init
{
	[super init];
	
	// 로그를 사용하면 초보자도 무슨 일이 일어나는지
	// 쉽게 이해할 수 있고 버그를 잡는 데도 도움이 된다.
	NSLog(@"init");
	
	// NSSpeechSynthesizer의 새 인스턴스를
	// 기본 목소리로 만든다.
	speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
	[speechSynth setDelegate:self];
	voiceList = [[NSSpeechSynthesizer availableVoices] retain];

	return self;
}

- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender 
		didFinishSpeaking:(BOOL)complete
{
	NSLog(@"complete = %d", complete);
	[stopButton setEnabled:NO];
	[startButton setEnabled:YES];
	[tableView setEnabled:YES];
}

- (IBAction)sayIt:(id)sender
{
	NSString * string = [textField stringValue];
	
	// 문자열의 길이가 0인가?
	if ([string length] == 0) {
		NSLog(@"string from %@ is zero-length", textField);
		return;
	}
	[speechSynth startSpeakingString:string];
	NSLog(@"Have started to say: %@", string);
	[stopButton setEnabled:YES];
	[startButton setEnabled:NO];
	[tableView setEnabled:NO];
}

- (IBAction)stopIt:(id)sender
{
	NSLog(@"stopping");
	[speechSynth stopSpeaking];
	[stopButton setEnabled:NO];
	[startButton setEnabled:YES];

}

- (int)numberOfRowsInTableView:(NSTableView *)tv
{
	return [voiceList count];
}

- (id)tableView:(NSTableView *)tv 
		objectValueForTableColumn:(NSTableColumn *)tableColumn
		row:(int)row
{
	NSString *v = [voiceList objectAtIndex:row];
	NSDictionary *dict = [NSSpeechSynthesizer attributesForVoice:v];
	return [dict objectForKey:NSVoiceName];
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
	int row = [tableView selectedRow];
	if (row == -1) {
		return;
	}
	NSString *selectedVoice = [voiceList objectAtIndex:row];
	[speechSynth setVoice:selectedVoice];
	NSLog(@"new voice = %@", selectedVoice);
}

- (void)awakeFromNib
{
	// 테이블 뷰가 화면에 나타날 때 기본 목소리가 
	// 선택되어야 한다.
	NSString *defaultVoice = [NSSpeechSynthesizer defaultVoice];
	NSLog(@"default voice = %@", defaultVoice);
	
	int defaultRow = [voiceList indexOfObject:defaultVoice];
	[tableView selectRow:defaultRow byExtendingSelection:NO];
	[tableView scrollRowToVisible:defaultRow];
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
	NSString *methodName = NSStringFromSelector(aSelector);
	NSLog(@"respondsToSelector:(%d) %@", [super respondsToSelector:aSelector], methodName);
	return [super respondsToSelector:aSelector];
}

@end
